//
//  ChatWallpaperViewController.m
//  Molian
//
//  Created by 胡津 on 15/3/5.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "ChatWallpaperViewController.h"


@interface ChatWallpaperViewController ()

@end

@implementation ChatWallpaperViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"聊天背景修改";
    self.view.backgroundColor = RGBA(32, 38, 45, 1);
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight-64)style:UITableViewStylePlain];
    self.tableview.backgroundColor = RGBA(32, 38, 45, 1);
    self.tableview.delegate = self;
    self.tableview.dataSource = self;
    self.tableview.scrollsToTop = YES;//是否点击状态栏置顶
    self.tableview.separatorStyle = UITableViewCellSeparatorStyleNone;//分割线
    [self.view addSubview:self.tableview];
    
    [self setSysBackgroundArray];
    
    // 从服务器拉取当前聊天背景图
    [self setCurrentChatBackground];
}

- (void)setSysBackgroundArray {
    // 从归档文件里面找, 如果没有则从服务器拉取
    self.sysChatBackgroundArray = [Utils readArchiveData:SYS_CHAT_BACKGROUND_DIR ForKey:SYS_CHAT_BACKGROUND_INFO];
    if (self.sysChatBackgroundArray) {
        // 如果已保存了系统背景, 则使用已有的
        [self.tableview reloadData];
    } else {
        // 从服务器获取系统图片
        AVQuery *query = [MLChatBackground query];
        [query whereKey:@"type" equalTo:[NSNumber numberWithInt:MLChatBackgroundType_STATIC_SYS]];
        [query whereKey:@"status" equalTo:[NSNumber numberWithInt:MLChatBackgroundStatus_NORMAL]];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                self.sysChatBackgroundArray = [[NSMutableArray alloc]init];
                for (MLChatBackground *chatBackground in objects) {
                    NSMutableDictionary *backgroundDic = [[NSMutableDictionary alloc]init];
                    [backgroundDic setValue:chatBackground.objectId forKey:@"backgroundId"];
                    [backgroundDic setValue:chatBackground.img.objectId forKey:@"backgroundImgId"];
                    [backgroundDic setValue:chatBackground.img.url forKey:@"backgroundImgUrl"];
                    [self.sysChatBackgroundArray addObject:backgroundDic];
                }
                
                // 本地化系统背景信息
                [Utils saveArchiveData:self.sysChatBackgroundArray DIR:SYS_CHAT_BACKGROUND_DIR forKey:SYS_CHAT_BACKGROUND_INFO];
                
                [self.tableview reloadData];
            } else {
                // Log details of the failure
                NSLog(@"Error: %@ %@", error, [error userInfo]);
            }
        }];
    }
}

- (void)setCurrentChatBackground {
    AVQuery *chatBgQuery = [MLChatBackground query];
    NSArray *userArray = [NSArray arrayWithObjects:self.currentUser, self.chatUser, nil];
    [chatBgQuery whereKey:@"owner" containedIn:userArray];
    [chatBgQuery whereKey:@"chatUser" containedIn:userArray];
    [chatBgQuery whereKey:@"status" equalTo:[NSNumber numberWithInt:MLChatBackgroundStatus_NORMAL]];
    [chatBgQuery addDescendingOrder:@"createdAt"];
    [HUD setOnViewWithTitle:@"" animated:YES];
    [chatBgQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        if (!error) {
            self.chatBackground = (MLChatBackground *)object;
        }
    }];
}

#pragma mark - table view delegate

- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIButton * titleBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 0, 100, 50)];
    [titleBtn setTitle:@"从相册选择" forState:0];
    [titleBtn setTitleColor:[UIColor whiteColor] forState:0];
    [titleBtn addTarget:self action:@selector(choosePhoto) forControlEvents:UIControlEventTouchUpInside];
    titleBtn.backgroundColor = RGBA(32, 38, 45, 0.9);
    
    return titleBtn;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSString *CellId = [NSString stringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]];//以indexPath来唯一确定cell
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId];
        
        NSMutableDictionary *chatBackground = [self.sysChatBackgroundArray objectAtIndex:indexPath.row];

        UIView *headview=[[UIView alloc]initWithFrame:CGRectMake(30, 30, 150-60, 150-60)];
        headview.backgroundColor=[UIColor blackColor];
        [headview.layer setCornerRadius:7];
        headview.layer.shadowColor = [[UIColor blackColor] colorWithAlphaComponent:1].CGColor;
        headview.layer.shadowOpacity = 2;
        headview.layer.shadowRadius = 2;
        headview.layer.shadowOffset = CGSizeMake(2, 3);
        
        UIImageView * Wallpaper=[[UIImageView alloc]initWithFrame:CGRectMake(30, 30, 150-60, 150-60)];
        [Wallpaper setContentMode:UIViewContentModeScaleAspectFill];
        Wallpaper.clipsToBounds = NO;
        Wallpaper.layer.masksToBounds = YES;//开启圆角
        [Wallpaper.layer setCornerRadius:7];
        [Wallpaper setUserInteractionEnabled:YES];
        [Wallpaper addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goToPhotoView:)]];
        Wallpaper.tag=indexPath.row+100;

        UIImageView * WallpaperBlur=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DeviceWidth, 150)];
        WallpaperBlur.clipsToBounds = YES;
        [cell.contentView addSubview:WallpaperBlur];
        [cell.contentView addSubview:headview];
        [cell.contentView addSubview:Wallpaper];
        
        //模糊黑色
        UIImageView *blackmask = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DeviceWidth, 150)];
        blackmask.image = [UIImage imageNamed:@"blackmask_shang"];
        blackmask.alpha = 0.7;
        [cell.contentView addSubview:blackmask];
        
        // 修改缓存图片插件
        [Wallpaper sd_setImageWithURL:[NSURL URLWithString:[chatBackground objectForKey:@"backgroundImgUrl"]] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
            if (image) {

                CGRect rect = CGRectMake(0, (image.size.height-150 *2)/2, image.size.height, 150 *2);
                CGImageRef imageRef = CGImageCreateWithImageInRect([Wallpaper.image CGImage], rect);
                UIImage *cropedImg = [UIImage imageWithCGImage:imageRef];
                
                UIImage *blueImg = [cropedImg stackBlur:10];
                WallpaperBlur.image = blueImg;
                [WallpaperBlur setContentMode:UIViewContentModeScaleAspectFill];
                
            }
        }];
        
        cell.backgroundColor=[UIColor clearColor];
        cell.selectedBackgroundView = [[UIView alloc] initWithFrame:cell.frame];
        cell.selectedBackgroundView.backgroundColor = [[UIColor blackColor]colorWithAlphaComponent:1];//点击后背景色
        
    }

    return  cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.sysChatBackgroundArray count];//cell个数
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;//每个cell的头部间距
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
{
    return 1;//每个cell的底部间距
}

//设置行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 150;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 设置系统图片作为聊天背景图
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.chatBackground) {
        // 删除旧图片
        if (MLChatBackgroundType_NORMAL == self.chatBackground.type) {
            [self.chatBackground.img deleteInBackground];
        }
    } else {
        self.chatBackground = [MLChatBackground object];
        self.chatBackground.status = MLChatBackgroundStatus_NORMAL;
    }
    self.chatBackground.owner = self.currentUser;
    self.chatBackground.chatUser = self.chatUser;
    // 添加背景记录
    self.chatBackground.type = MLChatBackgroundType_SYS;
    
    // 设置所属的系统图片
    NSMutableDictionary *chatBackgroundInfo = [self.sysChatBackgroundArray objectAtIndex:indexPath.row];
    AVFile *bgImg = [[AVFile alloc]init];
    bgImg.objectId = [chatBackgroundInfo objectForKey:@"backgroundImgId"];
    self.chatBackground.img = bgImg;
    [HUD setOnViewWithTitle:@"" animated:YES];
    [self.chatBackground saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        if (succeeded) {
            [HUD Prompt:@"设置成功"];
            // 保存到本地
            [Utils saveArchiveData:bgImg DIR:CHAT_BACKGROUND_DIR forKey:[NSString stringWithFormat:@"chatBackgroundImg_%@",self.userIDStr]];
            // 给聊天对象推送通知
            [self pushBackgroundUpdateNotification];
        } else {
            [HUD Prompt:@"设置失败, 请重试"];
        }
    }];
}

#pragma -mark user photo

-(void)choosePhoto
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:@"修改背景"
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"相册", @"拍照", nil];
    [choiceSheet showInView:self.view];

}

//修改背景
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    // 点击取消,返回
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }
    
    if ([actionSheet.title isEqualToString:@"修改背景"]) {
        
        UIImagePickerControllerSourceType sourceType  = UIImagePickerControllerSourceTypePhotoLibrary;
        if (buttonIndex == actionSheet.firstOtherButtonIndex+1) {
            sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        if ([UIImagePickerController isSourceTypeAvailable:sourceType])
        {
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            //            imagePickerController.allowsEditing = YES; //设置用户是否可以编辑图片
            imagePickerController.delegate = self;
            imagePickerController.sourceType = sourceType;
            [imagePickerController.view setTag:0];
            [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];
            [self presentViewController:imagePickerController animated:YES completion:nil];
            
        }else{
            [HUD Prompt:@"打开失败,请检查手机设置"];
        }
        
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    if (!image) {
        image = [info valueForKey:UIImagePickerControllerOriginalImage];
    }
    [self uploadPhoto:image];
}

//查看图片大图
-(void)goToPhotoView:(UITapGestureRecognizer *)tap
{
    UIImageView *bg = (UIImageView *)[self.view viewWithTag:tap.view.tag];

    JTSImageInfo *imageInfo = [[JTSImageInfo alloc] init];
    imageInfo.image = bg.image;
    imageInfo.referenceRect = bg.frame;
    imageInfo.referenceView = bg.superview;
    // Setup view controller
    JTSImageViewController *imageViewer = [[JTSImageViewController alloc]initWithImageInfo:imageInfo
                                                                                      mode:JTSImageViewControllerMode_Image
                                                                           backgroundStyle:JTSImageViewControllerBackgroundStyle_ScaledDimmed];
    // Present the view controller.
    [imageViewer showFromViewController:self transition:JTSImageViewControllerTransition_FromOriginalPosition];
}

//图片上传
-(void)uploadPhoto:(UIImage *)photo
{
    if (self.chatBackground) {
        // 删除旧图片
        if (MLChatBackgroundType_NORMAL == self.chatBackground.type) {
            [self.chatBackground.img deleteInBackground];
        }
    } else {
        self.chatBackground = [MLChatBackground object];
        self.chatBackground.status = MLChatBackgroundStatus_NORMAL;
    }
    // 设置所属用户
    self.chatBackground.owner = self.currentUser;
    self.chatBackground.chatUser = self.chatUser;
    // 添加背景记录
    self.chatBackground.type = MLChatBackgroundType_NORMAL;
    
    // 压缩处理用户图片
    CGSize imageSize = photo.size;
    imageSize.width = photo.size.width * DeviceHeight * 2 / photo.size.height;
    imageSize.height = DeviceHeight * 2;
    UIImage *bgImg = [self imageWithImage:photo scaledToSize:imageSize];
    
    float kCompressionQuality = 0.3;
    NSData *imgData = UIImageJPEGRepresentation(bgImg, kCompressionQuality);
    
    AVFile *imgFile = [AVFile fileWithName:@"chatBackgroundImage.jpg" data:imgData];
    self.chatBackground.img = imgFile;
    // 保存聊天图片
    [HUD setOnViewWithTitle:@"" animated:YES];
    [self.chatBackground saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        if (succeeded) {
            [HUD Prompt:@"保存成功"];
            [Utils saveArchiveData:photo DIR:CHAT_BACKGROUND_DIR forKey:[NSString stringWithFormat:@"chatBackgroundImg_%@",self.userIDStr]];
            // 给聊天对象推送通知
            [self pushBackgroundUpdateNotification];
            
        }else{
            [HUD Prompt:[NSString stringWithFormat:@"%@",@"网络异常"] ];
        }
    }];
}

#pragma mark - push

- (void)pushBackgroundUpdateNotification {
    AVPush * push = [[AVPush alloc]init];
    [push setChannel:self.userIDStr];
    NSDictionary *pushData = @{ @"action": NOTIFICATION_TYPE_CHAT_BACKGROUND_UPDATED,
                                @"userId": [MLUser currentUser].objectId,
                                };
    [push setData:pushData];
    [push sendPushInBackground];
}


-(UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}
@end
